import { app, BrowserWindow, ipcMain, dialog } from 'electron'
import path from 'path'
import fs from 'fs'

// 保持对窗口对象的全局引用
let mainWindow: BrowserWindow | null = null

// 用于存储图片路径的映射
const imagePathMap = new Map<string, string>()

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    frame: false, // 无边框窗口
    transparent: true, // 启用透明背景
    alwaysOnTop: true, // 窗口总在最前
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false, // 允许加载本地文件
      allowRunningInsecureContent: true, // 允许加载本地资源
    },
    backgroundColor: '#00000000', // 完全透明的背景色
    show: false, // 先不显示窗口
    hasShadow: false, // 禁用窗口阴影
  })

  // 设置窗口支持文件拖放
  mainWindow.webContents.on('will-navigate', (event) => {
    event.preventDefault()
  })

  // 在开发环境中加载本地服务器
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:5173')
    // 等待页面加载完成后再显示窗口
    mainWindow.webContents.on('did-finish-load', () => {
      mainWindow?.show()
    })
    mainWindow.webContents.openDevTools()
  } else {
    // 在生产环境中加载打包后的文件
    mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'))
    mainWindow.show()
  }

  // 窗口控制
  ipcMain.on('window-minimize', () => {
    mainWindow?.minimize()
  })

  ipcMain.on('window-maximize', () => {
    if (mainWindow?.isMaximized()) {
      mainWindow.unmaximize()
    } else {
      mainWindow?.maximize()
    }
  })

  ipcMain.on('window-close', () => {
    mainWindow?.close()
  })

  // 修改透明度控制为handle方式
  ipcMain.handle('set-window-opacity', async (event, opacity: number) => {
    if (mainWindow) {
      try {
        mainWindow.setOpacity(opacity)
        return true
      } catch (error) {
        console.error('Failed to set window opacity:', error)
        return false
      }
    }
    return false
  })

  // 修改点击穿透控制为handle方式
  ipcMain.handle('set-ignore-mouse-events', async (event, ignore: boolean) => {
    if (mainWindow) {
      try {
        mainWindow.setIgnoreMouseEvents(ignore, { forward: true })
        return true
      } catch (error) {
        console.error('Failed to set ignore mouse events:', error)
        return false
      }
    }
    return false
  })

  // 文件操作
  ipcMain.handle('open-file-dialog', async () => {
    const result = await dialog.showOpenDialog(mainWindow!, {
      properties: ['openFile', 'multiSelections'],
      filters: [
        { name: 'Images', extensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'] }
      ]
    })

    if (result.filePaths && result.filePaths.length > 0) {
      // 读取文件并创建 base64 数据
      for (const filePath of result.filePaths) {
        try {
          const data = await fs.promises.readFile(filePath)
          const base64Data = `data:image/${path.extname(filePath).slice(1)};base64,${data.toString('base64')}`
          imagePathMap.set(base64Data, filePath)
        } catch (error) {
          console.error('Error reading file:', error)
        }
      }
    }

    return result.filePaths
  })

  // 监听窗口关闭事件
  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 添加文件系统操作的基础结构
ipcMain.handle('save-project', async (event, data) => {
  const { filePath, content } = data
  // TODO: 实现项目保存逻辑
})

ipcMain.handle('load-project', async (event, filePath) => {
  // TODO: 实现项目加载逻辑
})

ipcMain.handle('save-canvas', async (event, content: string) => {
  if (!mainWindow) return false

  try {
    // 打开保存文件对话框
    const { filePath } = await dialog.showSaveDialog(mainWindow, {
      title: '保存画布',
      defaultPath: path.join(app.getPath('documents'), 'canvas.json'),
      filters: [
        { name: 'PureRef Canvas', extensions: ['json'] }
      ]
    })

    if (!filePath) return false

    // 写入文件
    await fs.promises.writeFile(filePath, content, 'utf-8')
    return true
  } catch (error) {
    console.error('Failed to save canvas:', error)
    return false
  }
})

// 添加文件系统操作的基础结构
ipcMain.handle('open-canvas', async () => {
  if (!mainWindow) return null

  try {
    // 打开文件对话框
    const { filePaths } = await dialog.showOpenDialog(mainWindow, {
      title: '打开画布',
      defaultPath: app.getPath('documents'),
      filters: [
        { name: 'PureRef Canvas', extensions: ['json'] }
      ],
      properties: ['openFile']
    })

    if (!filePaths || filePaths.length === 0) return null

    // 读取文件内容
    const content = await fs.promises.readFile(filePaths[0], 'utf-8')
    return content
  } catch (error) {
    console.error('Failed to open canvas:', error)
    return null
  }
})

// 添加文件系统操作的基础结构
ipcMain.handle('get-image-path', async (event, base64Data: string) => {
  // 如果已经缓存了路径，直接返回
  if (imagePathMap.has(base64Data)) {
    return imagePathMap.get(base64Data)
  }
  return null
}) 